/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : my_note_send.js                            
*  Description  : 보낸쪽지
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-07-16  김효순    Created.  
*******************************************************************************/

jQuery(function($){
	// 상단 링크
	function clsTopLink()
	{
		this._HTMLDom  = null;
		
		this._init();
	}
	
	clsTopLink.prototype = {
		_init: function(){
			var $layer = $("div#container article.depth2_tab");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			$layer.find("a").attr("id", "idPermissionLink");
		}
	}
	
	// 상단탭
	function clsTopTab()
	{
		this._HTMLDom  = null;
		
		this._init();
	}
	
	clsTopTab.prototype = {
		_init: function(){
			var $layer = $("div#container article.club_myclub ul.tab_menu02");
			this._HTMLDom = {
				"$layer": $layer
			}
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
	}
	
	// 쪽지 리스트
	function clsNoteList()
	{
		this._HTMLDom  = null;
		this.listData = null;
		this.totalCount = null;
		
		this._init();
	}
	
	clsNoteList.prototype = {
		_init: function(){
			var $layer = $("div#container article.club_myclub div.total");
			this._HTMLDom = {
				"$layer": $layer
				, "$element": $layer.find("tbody tr:first").clone(true)
				, "$noresult": $layer.find("article.board_list_none")
			}

			this.setList([], 0);
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setList: function(thisData, t){
			this.listData = thisData;
			this.totalCount = t;
			this.display();
		}
		, setMemberInfo: function(info, rKey){
			for(var i=0;i<this.listData.length;i++){
				if(this.listData[i]["수신코드"]+"" == rKey+"") break;
			}
			
			if(i<this.listData.length){
				this.listData[i]["회원정보"] = info;
				this.senderDisplay(i);
			}
		}
		, display: function(){
			var $layer = this.$getLayer();
			var $element = this._HTMLDom["$element"];
			var $noresult = this._HTMLDom["$noresult"];
			var thisClass = this;
			
			$layer.find("p:first em").html(this.totalCount);
			
			if(this.listData.length){
				$layer.find("table").show();
				$noresult.hide();
				
				$layer.find("tbody").empty();
				for(var i=0;i<this.listData.length;i++){
					$layer.find("tbody").append($element.clone(true));
				}
				$layer.find("tbody tr").each(function(n){
					var d = thisClass.listData[n];
					
					$(this).find("td:eq(1) span:eq(0) img").attr("src", _gf.getDefaultProfileImage());
					$(this).find("td:eq(1) span:eq(1)").html("");
					$(this).find("td:eq(2)").html(d["내용"]);
					$(this).find("td:eq(3)").html(d["발송일"] + "<span>" + d["발송시"] + "</span>");
					$(this).find("td:eq(4)").html(d["수신일"] + "<span>" + d["수신시"] + "</span>");
				});
			}else{
				$layer.find("table").hide();
				$noresult.show();
			}
		}
		, senderDisplay: function(n){
			var $layer = this.$getLayer();
			var d = this.listData[n]["회원정보"];
			
			$layer.find("tbody tr").eq(n).find("td:eq(1) span:eq(0) img").attr("src", _gf.filePath2Url(d["이미지"])).error(function(){
				$(this).attr("src", _gf.getDefaultProfileImage());
			});
			$layer.find("tbody tr").eq(n).find("td:eq(1) span:eq(1)").html(d["닉네임"]).hover(function(){
				_gf.showProfileLayer($(this), d, "left", 0, 0);
			}, function(){
				_gf.closeProfileLayer();
			});
		}
		, spinStart: function(){
			var $layer = this.$getLayer();
			var $noresult = this._HTMLDom["$noresult"];
			
			$layer.find("table").hide();
			$noresult.hide();
			
			if($layer.find("div#tmpSpin").length == 0){
				$layer.append("<div id='tmpSpin' style='position:relative; width:900px; height:150px;' />");
			}
			$layer.find("div#tmpSpin").show().spin();
		}
		, spinEnd: function(){
			var $layer = this.$getLayer();
			
			$layer.find("table").show();
			$layer.find("div#tmpSpin").hide().spin(false);
		}
		, getKeys: function(){
			var $layer = this.$getLayer();
			var thisClass = this;
			var r = "";
			
			$layer.find("input:checkbox:gt(0):checked").each(function(){
				var n = $layer.find("input:checkbox:gt(0)").index($(this));
				
				if(r) r += ",";
				r += thisClass.listData[n]["발송코드"];
			});
			
			return r;
		}
		, getKey: function(n){
			return this.listData[n]["발송코드"];
		}
		, checkCheck: function($this){
			var $layer = this.$getLayer();
			var n = $layer.find("input:checkbox").index($this);
			
			if(n == 0){
				var b = $layer.find("input:checkbox").eq(n).is(":checked");
				$layer.find("input:checkbox").attr("CHECKED", b);
			}else{
				var b = !($layer.find("input:checkbox:gt(0):not(:checked)").length);
				
				$layer.find("input:checkbox:eq(0)").attr("CHECKED", b);
			}
		}
	}
	
	
	// 서버통신
	function clsComm()
	{
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){
			
		}
		// 쪽지 리스트
		, getNoteList: function(arg){
			var thisClass = this;
			
			//ajax
			var serviceName = "getMySentMessageList";
			var options = {
				
			}
			_gf.ajax({
				"sid": "US001"
				, "servicename": serviceName
				, "listcount": arg["페이지당수"]
				, "currpageno": arg["페이지"]
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
					, "전체수": ret["msp"]["contents"]["@totalcount"]
					, "결과값": []
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items){
					if(!items.length) items = new Array(items);
					for(var i=0;i<items.length;i++){
						var obj = items[i];
						var d = _util.nvl(obj["sendDate"])+"";
						var t = _util.nvl(obj["sendTime"])+""
						var rd = _util.nvl(obj["messageIn"]["recDate"])+"";
						var rt = _util.nvl(obj["messageIn"]["recTime"])+""

						res["결과값"].push({
							 "수신코드": _util.nvl(obj["messageIn"]["messageInSeq"])
							, "발송코드": _util.nvl(obj["messageOutSeq"])
							, "회원정보": {
								"아이디": _util.nvl(obj["messageIn"]["recUserId"])
							}
							, "내용": _util.enter2br(_util.nvl(obj["messageBody"]))
							, "발송일": d.substrEx(0, 4) + "-" + d.substrEx(4, 2) + "-" + d.substrEx(6, 2)
							, "발송시": t.substrEx(0, 2) + ":" + t.substrEx(2, 2)
							, "수신일": rd.substrEx(0, 4) + "-" + rd.substrEx(4, 2) + "-" + rd.substrEx(6, 2)
							, "수신시": rt.substrEx(0, 2) + ":" + rt.substrEx(2, 2)
						});
					}
				}
				
				document.objControl.finishNoteList(res);
			});
		}
		// 쪽지보관
		, saveNote: function(arg){
			var thisClass = this;
			
			//ajax
			var serviceName = "saveMessage";
			var options = {
				"messageOutSeq": arg["발송코드"]
			}
			_gf.ajax({
				"sid": "MG001"
				, "servicename": serviceName
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
				}
				
				document.objControl.finishSaveNote(res);
			});
		}
		// 쪽지삭제
		, noteDelete: function(arg){
			var thisClass = this;
			
			//ajax
			var serviceName = "deleteMessage";
			var options = {
				"messageOutSeq": arg["발송코드"]
				, "inOutFlag": arg["송수신코드"]
			}
			_gf.ajax({
				"sid": "MG001"
				, "servicename": serviceName
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
				}
				
				document.objControl.finishNoteDelete(res);
			});
		}
	}
	
	// 컨트롤
	function clsControl()
	{
		this.objComm = null;
		this.objTopLink = null;
		this.objTopTab = null;
		this.objNoteList = null;
		this.objNotePaging = null;
		
		this.params = null;
		
		
		this._permitStart = null;
	}
	
	clsControl.prototype = {
		_init: function(){
			this._preload();
			
			this.objComm = new clsComm();
			this.objTopLink = new clsTopLink();
			this.objTopTab = new clsTopTab();
			this.objNoteList = new clsNoteList();
			this.objNotePaging = new _gf.makePaging($("div#idNotePaging"), 10, 10);
			
			this._beforeStart();
			this._bind();
		}
		, _preload: function(){
			_gf.spinStart();
			
			$("div#container ul.pagenum_area").wrap("<div id='idNotePaging' />").remove();
		}
		, _beforeStart: function(){
			var thisClass = this;
			this._permitStart = {
				
			}
			
			$.ajax({
				url: _ROOT + "/js/mypage_common.js"
				, dataType: "script"
				, async: false
				, success: function(){
					
				}
				, error: function(){
					alert("error");
				}
			});
			
			_util.executeThread(function(){
				for(var k in thisClass._beforeStart){
					if(!thisClass._beforeStart[k]) return false;
				}
				
				return (_gf.getMyInfoData());
			}, function(){
				_gf.spinEnd();
				thisClass._start();
			});
		}
		, _bind: function(){
			var thisClass = this;
			
			// 상단탭
			this.objTopTab.$getLayer().on("click", "a", function(){
				var n = thisClass.objTopTab.$getLayer().find("a").index($(this));
				
				switch(n){
					case 0:
						thisClass.goRecvPage();
						break;
					case 1:
						thisClass.goSendPage();
						break;
					case 2:
						thisClass.goSavePage();
						break;
				}
			});
			
			// 선택
			this.objNoteList.$getLayer().on("click", "input:checkbox", function(){
				thisClass.objNoteList.checkCheck($(this));
			});
			
			// 쪽지보관, 삭제
			$("div#container").on("click", "img[alt='쪽지 보관'], img[alt='삭제']", function(){
				var bName = $(this).attr("alt");
				
				switch(bName){
					case "쪽지 보관":
						thisClass.noteSave();
						break;
					case "삭제":
						thisClass.noteDelete();
						break;
				}
			});
			
			// 쪽지보기
			this.objNoteList.$getLayer().on("click", "tbody tr", function(e){
				e = e || event;
				
				if(e.target.tagName.toUpperCase() == "INPUT") return;
				
				var n = thisClass.objNoteList.$getLayer().find("tbody tr").index($(this));
				var k = thisClass.objNoteList.getKey(n);
				
				thisClass.goViewPage(k);
			});
			
			// 페이지이동
			$(this.objNotePaging).bind("evtPageClick", function(){
				thisClass.getNoteList();
			});
		}
		, _start: function(){
			this.objNotePaging.setPage(1);
			
			// 쪽지 리스트
			this.getNoteList();
		}
		// 쪽지 리스트
		, getNoteList: function(){
			this.objNoteList.spinStart();
			this.objComm.getNoteList({
				"페이지당수": this.objNotePaging.getCountPerPage()
				, "페이지": this.objNotePaging.getPage()
			});
		}
		// 쪽지보관
		, noteSave: function(){
			var k = this.objNoteList.getKeys();
			
			if(!k){
				alert("보관할 쪽지를 선택해 주십시요.");
				return;
			}
			
			_gf.spinStart("saving...");
			this.objComm.saveNote({
				"발송코드": k
			});
		}
		// 쪽지삭제
		, noteDelete: function(){
			var k = this.objNoteList.getKeys();
			
			if(!k){
				alert("삭제할 쪽지를 선택해 주십시요.");
				return;
			}
			
			_gf.spinStart("deleting...");
			this.objComm.noteDelete({
				"발송코드": k
				, "송수신코드": "OUT"
			});
		}
		// 쪽지 완료
		, finishNoteList: function(ret){
			var thisClass = this;
			
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			this.objNotePaging.setTotalCount(ret["전체수"]);
			this.objNotePaging.display();
			
			this.objNoteList.spinEnd();
			this.objNoteList.setList(ret["결과값"], ret["전체수"]);
			
			// 회원정보
			for(var i=0;i<ret["결과값"].length;i++){
				var d = ret["결과값"][i];
				
				_gf.getMemberInfo({
					"아이디": d["회원정보"]["아이디"]
					, "수신코드": d["수신코드"]
					, "콜백": function(res, info, arg){
						thisClass.objNoteList.setMemberInfo(info, arg["수신코드"]);
					}
				});
			}
		}
		// 쪽지 보관 완료
		, finishSaveNote: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			_gf.spinEnd();
			
			// 쪽지 리스트
			this.getNoteList();
		}
		// 쪽지 삭제 완료
		, finishNoteDelete: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			_gf.spinEnd();
			
			// 쪽지 리스트
			this.getNoteList();
		}
		// 받은쪽지 이동
		, goRecvPage: function(){
			var szLink = _ROOT + "/mypage/my_note.html";
			document.location.href = szLink;
		}
		// 보낸쪽지 이동
		, goSendPage: function(){
			var szLink = _ROOT + "/mypage/my_note_send.html";
			document.location.href = szLink;
		}
		// 보관함 이동
		, goSavePage: function(){
			var szLink = _ROOT + "/mypage/my_note_keep.html";
			document.location.href = szLink;
		}
		// 쪽지보기
		, goViewPage: function(seq){
			var szLink = _ROOT + "/popup/pop_note_view.html?q_type=OUT&q_seq=" + seq;
			var winNoteView = window.open(szLink, "winNoteView", "width=500, height=300, scrollbars=0");
			if(winNoteView) winNoteView.focus();
		}
	}
	
	document.objControl = new clsControl();
	document.objControl._init();
});
